<?php

declare(strict_types=1);

namespace App\Traits\Model\Users;

use App\Scopes\Users\Payer as PayerScope;
use Hyperf\Collection\Arr;
use Hyperf\Database\Model\Events\Saving;

trait Payer
{
    /**
     * The "booting" method of the model.
     */
    protected function boot():void
    {
        parent::boot();
        static::addGlobalScope(new PayerScope);
    }

    /**
     * 设置用户ID
     * @param $value
     */
    public function setUserIdAttribute($value)
    {
        if (!$value) {
            $value = match (getApp()) {
                'mini' => getInfo('mini', 'user_id')
            };
        }

        $this->attributes['user_id'] = $value;
    }

    /**
     * 设置openid
     * @param $value
     */
    public function setOpenidAttribute($value)
    {
        if (!$value) {
            $value = match (getApp()) {
                'mini' => getInfo('mini', 'openid'),
                'api' => ''
            };
        }

        $this->attributes['openid'] = $value;
    }

    /**
     * 写入前操作
     * @param Saving $saving
     */
    public function saving(Saving $saving)
    {
        /** @var static $model */
        $model = $saving->getModel();
        $change = $model->getChanges();

        if ($model->is_default) {
            if ($model->is_default) { // 如果该条数据设置为默认值则去除原始默认值为1的数据, 保证默认值唯一
                $this->where('openid', $model->openid?:getInfo('mini', 'openid'))
                    ->where('is_default', 1)
                    ->update(['is_default' => 0]);
            } elseif ($this->where('openid', $model->openid?:getInfo('mini', 'openid'))
                ->where('is_default', 1)
                ->doesntExist()) {
                // 如果该条数据未设置默认值则查询是否有默认值,如果没有则设置当前数据为默认值
                $this->is_default = 1;
            }
        }
    }
}
